package swu.cx.roomwords

import android.content.Context
import androidx.lifecycle.LiveData
import kotlinx.coroutines.*

class WordsRepository private constructor(){
    var scope:CoroutineScope
    val job = Job()
    var wordDao:WordDao
    var allLiveWords:LiveData<List<Word>>
        private set
    init {
        scope = CoroutineScope(Dispatchers.Main+job)
        val wordDataBase =WordDataBase.getWordDataBaseInstance(context)
        wordDao = wordDataBase.getWordDao()
        allLiveWords = wordDao.getAllWords()
    }
    companion object{
        private var instance:WordsRepository?=null
        lateinit var context: Context
        fun getWordInstance(context: Context):WordsRepository{
            this.context = context
            if (instance == null){
                synchronized(this){
                    if (instance==null){
                        instance = WordsRepository()
                    }
                }
            }
            return instance!!
        }
    }

    fun insert(vararg words: Word) {
        scope.launch(Dispatchers.IO) {
            wordDao.insertWords(*words)
        }
    }

    fun clear() {
        scope.launch(Dispatchers.IO) {
            wordDao.deleteAllWords()
        }
    }

    fun modify(vararg words: Word) {
        scope.launch(Dispatchers.IO) {
            wordDao.update(*words)
        }
    }

    fun delete(vararg words: Word) {
        scope.launch(Dispatchers.IO) {
            wordDao.deleteWords(*words)
        }
    }
    fun findWordWithPattern(pattern:String)=wordDao.findWordWithPattern("%$pattern%")
}